package org.mtdownload.chartview;

import java.awt.BorderLayout;
import java.awt.Color;
import java.util.HashMap;

import javax.swing.JPanel;
import javax.swing.JScrollPane;

import org.mtdownload.download.DownloadManager;
import org.mtdownload.download.DownloadTask;
import org.mtdownload.download.DownloadTaskPropertiesChanged;

public class MTDownloadChartView extends JPanel {

	private static final long serialVersionUID = 3257006557622253623L;
	private DownloadTask curentlySelectedTask=null;    
	private ChartPanel chartCanvas=null;
	private HashMap<DownloadTask,TaskSeries> tasksMap=new HashMap<DownloadTask,TaskSeries>(); 
	private JScrollPane chartCanvasScroll=null;
	
	public MTDownloadChartView() {
		init();
	}
	
	private void init(){
		DownloadManager.addDownloadTaskPropertiesChangedListener(new DownloadTaskPropertiesChanged(){
			public void propertiesChanged(DownloadTask task) {
				if(!task.isAllThreadsSpawned()) return;
				if(tasksMap.get(task)==null){
					tasksMap.put(task,new TaskSeries());
				}
				TaskSeries series=tasksMap.get(task);
				if(task.getThreadsSpeed()!=null){
					series.addSpeeds(task.getThreadsSpeed());
				}
				if(task.equals(curentlySelectedTask)){
					chartCanvas.setSeries(series);
					chartCanvas.repaint();
				}
			}
		});		
		chartCanvas=new ChartPanel();		
		chartCanvas.setBackground(Color.WHITE);
		setLayout(new BorderLayout());
		chartCanvasScroll=new JScrollPane(chartCanvas);
		add(chartCanvasScroll,BorderLayout.CENTER);
		//add(threadsListScroll,BorderLayout.EAST);
	}
	
	/**
	 * @return Returns the curentlySelectedTask.
	 */
	public DownloadTask getCurentlySelectedTask() {
		return curentlySelectedTask;
	}
	

	/**
	 * @param curentlySelectedTask The curentlySelectedTask to set.
	 */
	public void setCurentlySelectedTask(DownloadTask curentlySelectedTask) {
		this.curentlySelectedTask = curentlySelectedTask;
		if(curentlySelectedTask==null){
			chartCanvas.setSeries(null);
			chartCanvasScroll.getViewport().doLayout();
			chartCanvas.repaint();
			return;
		}
		if(tasksMap.get(curentlySelectedTask)==null){
			tasksMap.put(curentlySelectedTask,new TaskSeries());
		}
		TaskSeries series=tasksMap.get(curentlySelectedTask);
		if(curentlySelectedTask.getThreadsSpeed()!=null){
			series.addSpeeds(curentlySelectedTask.getThreadsSpeed());
		}
		chartCanvas.setSeries(series);
		//chartCanvasScroll.getViewport().invalidate();
		chartCanvasScroll.getViewport().doLayout();
		//chartCanvasScroll.getViewport().revalidate();
		chartCanvas.repaint();
	}
}
